package com.ustc.hewei.nettyrpc2_0.zookeeper.config;

import com.ustc.hewei.nettyrpc2_0.common.config.PropertyFactory;
import com.ustc.hewei.nettyrpc2_0.common.utils.Constants;
import com.ustc.hewei.nettyrpc2_0.common.utils.PropertiesUtil;
import com.ustc.hewei.nettyrpc2_0.common.warp.ZkNode;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
* @description: zookeeper配置类
* @author hewei
* @date 2022/9/14 09:46
* @version 1.0
*/

@Configuration
public class CuratorConfig {

    /**
     * 初始化curator客户端
     * @return
     */
    @Bean
    public CuratorFramework getCuratorClient() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(PropertiesUtil.getInt(Constants.zkSleepTimeout), PropertiesUtil.getInt(Constants.zkMaxRetries));

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(PropertiesUtil.getString(Constants.zkAddress))
                .connectionTimeoutMs(PropertiesUtil.getInt(Constants.zkConnectTimeout))
                .sessionTimeoutMs(PropertiesUtil.getInt(Constants.zkSessionTimeout))
                .namespace(PropertiesUtil.getString(Constants.zkNamespace))
                .retryPolicy(retryPolicy).build();
        client.start();
        return client;
    }

    @Bean
    public ServiceDiscovery<ZkNode> serviceDiscovery(@Autowired CuratorFramework client) throws Exception {
        ServiceDiscovery<ZkNode> serviceDiscovery = ServiceDiscoveryBuilder
                .builder(ZkNode.class)
                .client(client).basePath("/service")
                .serializer(new JsonInstanceSerializer<>(ZkNode.class))
                .build();
        serviceDiscovery.start();
        return serviceDiscovery;
    }
}
